package designpattern

import "time"

type Flyweight interface {
	Operate() string
}

type PersonFlyweight struct {
	IdNo string
	Name string
}

func (person *PersonFlyweight) Operate() string {
	return person.Name
}

func newPersonFlyweight(IdNo string) *PersonFlyweight {
	println("Wait for 10 seconds to connect to the database and get data")
	time.Sleep(time.Second * 10)
	return &PersonFlyweight{IdNo: IdNo, Name: mockGetPersonNameByIdNo(IdNo)}
}

var mockPersonData = map[string]string{"1": "Nick", "2": "John", "3": "Benjamin", "4": "Martin", "5": "Lisa"}

func mockGetPersonNameByIdNo(idNo string) string {
	if v, ok := mockPersonData[idNo]; ok {
		return v
	} else {
		return "Unknow"
	}
}

var flyweightPool = make(map[string]Flyweight)

func GetFlyweightByFactory(idNo string) Flyweight {
	if v, ok := flyweightPool[idNo]; ok {
		return v
	} else {
		pf := newPersonFlyweight(idNo)
		flyweightPool[idNo] = pf
		return flyweightPool[idNo]
	}
}
